from tools_algorithm import *


class Solution:
    def maximumSubarraySum(self, nums: List[int], k: int) -> int:
        ss = list(accumulate(nums))
        h, ssh = {}, {}
        ans = -inf
        for i, v in enumerate(nums):
            a, b = v - k, v + k
            ai, bi = h.get(a, -1), h.get(b, -1)
            if ai > -1:
                ans = max(ans, ss[i] - ss[ai] + ssh.get(ai))
            if bi > -1:
                ans = max(ans, ss[i] - ss[bi] + ssh.get(bi))
            if v not in h:
                ssh[i] = v
            else:
                vi = h[v]
                ssh[i] = max(v, ssh[vi] + ss[i] - ss[vi], ss[i] - ss[vi] + nums[vi])
            h[v] = i
        return ans if ans != -inf else 0


s = Solution()
print(s.maximumSubarraySum([2, 10, 9, 2, 6], 4))
